//
//  BottomView.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/4.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "BottomView.h"
#import "BottomGoodsCollectionViewCell.h"

#import "TbCategoryTitleModel.h"
#import "TbGoodsListModel.h"

static NSString *bottomGoodsCellID = @"bottomGoodsCellID";

@interface BottomView ()<UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *titileScrollView;
@property (strong, nonatomic) UIView *sliderView;

@property (strong, nonatomic) UIView *lineV;

@property (strong, nonatomic) UIView *headerView;

@property (strong, nonatomic) UICollectionView *goodsCollectionView;

@property (strong, nonatomic) NSArray *arr;

@property (strong, nonatomic) NSMutableArray *labelArr;

@property (assign, nonatomic) CGFloat labelTotolWidth;
@property (strong, nonatomic) NSMutableArray *labelxArr;

// 用于标记在价格是选中状态下，显示不同的图片  YES 表示价格升序  NO表示价格降序
@property (assign, nonatomic) BOOL priceIsSelected;

@property (strong, nonatomic) UIButton *selectedBtn;

//@property (nonatomic, strong) NSMutableArray *dataArr;

@property (assign, nonatomic) NSInteger page;

@property (copy, nonatomic) NSString *classID;

@end


@implementation BottomView

- (instancetype)init {
    
    if (self == [super init]) {
        
        self.labelArr = [NSMutableArray array];
        self.labelxArr = [NSMutableArray array];
        
        self.page = 1;

        self.labelTotolWidth = 0.0;
        
        [self addSubview:self.titileScrollView];
        [self addSubview:self.sliderView];
        [self addSubview:self.lineV];
        [self addSubview:self.headerView];
        [self addSubview:self.goodsCollectionView];
        [self setupUI];
    }
    return self;
}

- (void)setCategoryTitleArr:(NSArray *)categoryTitleArr {
    
    _categoryTitleArr = categoryTitleArr;

    self.arr = categoryTitleArr;
    
    [self setupTitleScrollView];
    
    
}

- (void)setGoodsArr:(NSMutableArray *)goodsArr {
    
    _goodsArr = goodsArr;
    
    [self.goodsCollectionView reloadData];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    
}

- (void)setSupportType:(NSInteger)supportType {
    
    _supportType = supportType;
}

- (void)loadMoreData {
    
    self.page ++;
    [self.goodsCollectionView reloadData];
    
    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.goodsCollectionView.mj_footer endRefreshing];
    
}

#pragma mark -分类标题点击事件
- (void)labelGestureClick:(UIGestureRecognizer *)gesture {
    
    NSLog(@"分类标题点击事件");
    
    UILabel *label = (UILabel *)gesture.view;
    
    [self.goodsArr removeAllObjects];
    [self.goodsCollectionView reloadData];
    
    TbCategoryTitleModel *model = self.arr[label.tag];
    self.classID = model.classid;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NSShoppingBottomViewNotification" object:@{@"classId" : model.classid}];
    
    NSArray *arrL = [self.labelArr copy];
    for (int i = 0 ; i < [arrL count]; i ++) {
        
        if ([self.titileScrollView.subviews[i] isKindOfClass:[UILabel class]]) {
            UILabel *temp = self.titileScrollView.subviews[i] ;
            temp.textColor = Color333333;
        }
        
    }
    
    label.textColor = Colorff0000;
    
    CGFloat width = self.titileScrollView.frame.size.width;
    CGFloat offsetX = label.center.x - width * 0.5;
    // 最大偏移量
    CGFloat maxOffsetx = self.titileScrollView.contentSize.width - width;
    if (offsetX < 0) {
        offsetX = 0;
    } else if (offsetX > maxOffsetx) {
        offsetX = maxOffsetx;
    }
    
    [self.titileScrollView setContentOffset:CGPointMake(offsetX, 0) animated:NO];

    CGFloat x = [self.labelxArr[label.tag] floatValue];

    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = weakSelf.sliderView.frame;
        rect.origin.x = x;
        rect.size.width = label.width;
        weakSelf.sliderView.frame = rect;
    }];
    
    
}

#pragma mark -分类标题scrollview布局
- (void)setupTitleScrollView {
    
    CGFloat leftMargin = Margin;
    
    self.labelTotolWidth = leftMargin;
    
    for (int i = 0; i < self.arr.count; i ++) {
        
        UILabel *label = [[UILabel alloc] init];
        label.tag = i;
        label.userInteractionEnabled = YES;
//        label.text = self.arr[i];


        TbCategoryTitleModel *titileModel = self.arr[i];
        label.text = titileModel.classname;

        
        label.font = Font(24);
        label.textAlignment = NSTextAlignmentCenter;
        [label sizeToFit];

        [self.labelArr addObject:label];
        
        CGFloat labelMargin = jisuan(90);
    
        if (i == 0) {
            
            label.textColor = Colorff0000;
        
        }else {
            
            label.textColor = Color333333;
            
            UILabel *tempL = self.labelArr[i - 1];
            self.labelTotolWidth = self.labelTotolWidth + tempL.width+ labelMargin;
            
        }
        
        [self.labelxArr addObject:[NSString stringWithFormat:@"%.2f",self.labelTotolWidth]];

        label.frame = CGRectMake(self.labelTotolWidth, 0, label.size.width, jisuan(100));
        [self.titileScrollView insertSubview:label atIndex:i];
        
        UITapGestureRecognizer *labelGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelGestureClick:)];
        [label addGestureRecognizer:labelGesture];
    
    }
    
    UILabel *temp = [self.labelArr lastObject];
    CGFloat scrollviewWith = self.labelTotolWidth + Margin + temp.width;
    
    CGSize size = CGSizeMake(scrollviewWith, 0);
    self.titileScrollView.contentSize = size;
    
    [self.titileScrollView addSubview:self.sliderView];
    UILabel *label = [self.titileScrollView.subviews firstObject];
    self.sliderView.frame = CGRectMake(label.x, jisuan(75), label.width, jisuan(4));

}

#pragma mark -分类、综合按钮的点击
- (void)btnClick:(UIButton *)btn {
    
    if (btn!= self.selectedBtn) {
        
        self.selectedBtn.selected = NO;
        btn.selected = YES;
        self.selectedBtn = btn;
        
    }else{
        
        self.selectedBtn.selected = YES;
        
    }
    
    if (btn.tag == 0) {
        
        NSLog(@"综合");
        self.priceIsSelected = YES;
        
        // 综合数据请求
        
    }else if (btn.tag == 1) {
        
        NSLog(@"销量");
        self.priceIsSelected = YES;
        
        // 销量数据请求
        
    }else if (btn.tag == 2) {
        
        if (self.priceIsSelected) {
            
            NSLog(@"升序");
            
            [btn setImage:[UIImage imageNamed:@"priceUp"] forState:UIControlStateSelected];
            
            self.priceIsSelected = NO;
            
            // 价格升序数据请求
            
            
        }else {
            
            NSLog(@"降序");
            
            [btn setImage:[UIImage imageNamed:@"priceDown"] forState:UIControlStateSelected];
            
            self.priceIsSelected = YES;
            
            // 价格降序数据请求
        }
        
    }else  {
        
        NSLog(@"筛选");
        self.priceIsSelected = YES;
        
        // 筛选数据请求
        
    }
    
}
- (void)setupUI {
    
    __weak typeof(self) weakSelf = self;
    [self.titileScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.mas_left);
        make.right.mas_equalTo(weakSelf.mas_right);
        make.top.mas_equalTo(weakSelf.mas_top);
        make.height.mas_equalTo(jisuan(100));
    }];
    
    [self.lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.mas_left);
        make.right.mas_equalTo(weakSelf.mas_right);
        make.top.mas_equalTo(weakSelf.titileScrollView.mas_bottom);
        make.height.mas_equalTo(jisuan(1));
    }];
    
//    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
//
//        make.left.mas_equalTo(weakSelf.mas_left);
//        make.right.mas_equalTo(weakSelf.mas_right);
//        make.top.mas_equalTo(weakSelf.lineV.mas_bottom);
//        make.height.mas_equalTo(jisuan(60));
//    }];

    [self.goodsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.mas_left).with.offset(Margin);
        make.right.mas_equalTo(weakSelf.mas_right).with.offset(-Margin);
        make.top.mas_equalTo(weakSelf.titileScrollView.mas_bottom).with.offset(10);
        make.bottom.mas_equalTo(weakSelf.mas_bottom);
        
    }];
    
//    [self createWithtitle:@"综合" image:nil withTag:0];
//    [self createWithtitle:@"销量" image:nil withTag:1];
//    [self createWithtitle:@"价格" image:[UIImage imageNamed:@"priceNormal"] withTag:2];
//    [self createWithtitle:@"优惠" image:nil withTag:3];
    
}

- (void)createWithtitle:(NSString *)name image:(UIImage *)image withTag:(NSInteger)tag {
    
    UIButton *btn = [[UIButton alloc] init];
    btn.titleLabel.font = Font(24);
    btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [btn setTitle:name forState:UIControlStateNormal];
    [btn setTitleColor:Color333333 forState:UIControlStateNormal];
    [btn setTitleColor:Colorff0000 forState:UIControlStateSelected];
    
    btn.tag = tag;
    
    CGFloat width = jisuan(80);
    CGFloat margin = (WIDTH - SmallMargin * 2 - Margin * 2 - width * 4) / 3.0;
    CGFloat x = SmallMargin + (width + margin) * tag;
    btn.frame = CGRectMake(x, 0, width, jisuan(60));
    [self.headerView addSubview:btn];
    
    if (image) {
        
        [btn setImage:image forState:UIControlStateNormal];
    }
    
    if (tag == 0) {
        
        // 设置“综合”为默认选中状态
        btn.selected = YES;
        self.selectedBtn = btn;
        
    }else {
        
        btn.selected = NO;
        
    }
    
    
    if (tag == 0) {
        
        // 综合
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
    }else if (tag == 3) {
        
        // 筛选
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.imageView.frame.size.width - btn.frame.size.width + btn.titleLabel.frame.size.width + jisuan(15), 0, 0);
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -btn.titleLabel.frame.size.width - btn.frame.size.width +  jisuan(20));
        
    }else if (tag == 2) {
        
        // 价格
        
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.imageView.frame.size.width - btn.frame.size.width + btn.titleLabel.frame.size.width + jisuan(15), 0, 0);
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -btn.titleLabel.frame.size.width - btn.frame.size.width + jisuan(20));
        
    }
    
    
    if (tag == 2) {
        
        // 价格
        [btn setImage:[UIImage imageNamed:@"priceUp"] forState:UIControlStateSelected];
        
    }else if (tag == 3) {
        
        // 筛选
        [btn setImage:nil forState:UIControlStateSelected];
        
    }
    
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
}


#pragma mark -collectionView delegate、datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 设置尾部控件的显示和隐藏
//    self.goodsCollectionView.mj_footer.hidden = self.dataArr.count == 0;
//    return self.dataArr.count;
    
    self.goodsCollectionView.mj_footer.hidden = self.goodsArr.count == 0;
    return self.goodsArr.count;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    BottomGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:bottomGoodsCellID forIndexPath:indexPath];

    cell.backgroundColor = WhiteColor;
    cell.layer.cornerRadius = jisuan(10);
    cell.layer.masksToBounds = YES;
    
//    cell.model = self.dataArr[indexPath.item];
    cell.model = self.goodsArr[indexPath.item];
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"bottomViewCell点击事件");

    if (self.supportType == 0) {
        
        ShoppingGoodsContentViewController *vc = [[ShoppingGoodsContentViewController alloc] init];
        [self.parentVC.navigationController pushViewController:vc animated:YES];
        
        NSLog(@"自营===bottomViewCell点击事件");
        
    }else {
        
        NSLog(@"非自营===bottomViewCell点击事件");

        // 优先拉起手淘：@"taobao_scheme" \\\ 天猫：tmall_scheme
//        [CommonAction sharedInstance].linkType = @"taobao_scheme";
//
//        [[CommonAction sharedInstance] goToTbGoodsDetailWith:self.parentVC itemDetailPage:@"41576306115"];
        
//        TbGoodsListModel *model = self.dataArr[indexPath.item];
        
        TbGoodsListModel *model = self.goodsArr[indexPath.item];
   
        [[CommonAction sharedInstance] goToTbGoodsDetailWith:self.parentVC itemDetailPage:model.coupon_click_url];
    
    }
    
}

#pragma mark -lazy
- (UIScrollView *)titileScrollView {
    
    if (!_titileScrollView) {
     
        _titileScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, jisuan(100))];
        _titileScrollView.backgroundColor = WhiteColor;
        
        _titileScrollView.showsVerticalScrollIndicator = NO;
        _titileScrollView.showsHorizontalScrollIndicator = NO;
        
    }
    
    return _titileScrollView;
}

- (UIView *)sliderView {
    
    if (!_sliderView) {
        
        _sliderView = [[UIView alloc] init];
        _sliderView.backgroundColor = Colorff0000;
        
    }
    
    return _sliderView;
    
}

- (UIView *)lineV {
    
    if (!_lineV) {
        
        _lineV = [[UIView alloc] init];
        _lineV.backgroundColor = Colordddddd;
        
    }
    
    return _lineV;
}

- (UIView *)headerView {
    
    if (!_headerView) {
        
        _headerView = [[UIView alloc] init];
        _headerView.backgroundColor = WhiteColor;
        
    }
    
    return _headerView;
}

- (UICollectionView *)goodsCollectionView {
    
    if (!_goodsCollectionView) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(jisuan(350), jisuan(520));
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        flowLayout.minimumLineSpacing = jisuan(10);
        flowLayout.minimumInteritemSpacing = jisuan(10);
        
        _goodsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _goodsCollectionView.tag = 2018;
        _goodsCollectionView.backgroundColor = Colorf2f2f2;
        
        _goodsCollectionView.delegate = self;
        _goodsCollectionView.dataSource = self;
        
//        _goodsCollectionView.bounces = NO;
//        _goodsCollectionView.alwaysBounceVertical = YES;
        _goodsCollectionView.scrollEnabled = NO;
        
        _goodsCollectionView.showsVerticalScrollIndicator = NO;
        _goodsCollectionView.showsHorizontalScrollIndicator = NO;
        
        [_goodsCollectionView registerClass:[BottomGoodsCollectionViewCell class] forCellWithReuseIdentifier:bottomGoodsCellID];
        
        if (@available (iOS 11.0, *)) {
            
            _goodsCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    
    return _goodsCollectionView;
    
}

//- (NSMutableArray *)dataArr {
//    
//    if (!_dataArr) {
//        
//        _dataArr = [NSMutableArray array];
//    }
//    return _dataArr;
//}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
